package com.demo.crm.springboot3security.security;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.demo.crm.springboot3security.mapper.UserMapper;

import lombok.RequiredArgsConstructor;

import java.util.Optional;

@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return Optional.ofNullable(userMapper.findByUsername(username))
                .map(user -> {
                    user.setRoles(userMapper.findRolesByUsername(username));
                    return new CustomUserDetails(user);
                })
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在: " + username));
    }
} 